var tablename = "student";
var app = this;
var $ = require("../../include/$");
var md5 = require("MD5");
module.exports = {
	get: function (req, res) {
		var reqdata = req.query;
		if (reqdata.type == 2) {
			tablename = "teacher";
		} else {
			tablename = "student"
		};
		console.log("查询表“", tablename, "”的数据", req.body, req.query);
		var finnerDate = req.models[tablename].find({
			name: reqdata.name
		});
		finnerDate.run(function (err, result) {
			if (err) {
				res.send(500, err);
			} else if (!result.length) {
				res.send(404, "用户名不正确");
			} else {
				reqdata.pwd = md5(reqdata.pwd);
				if (result[0].pwd === reqdata.pwd) {
					res.send(result);
				} else {
					res.send(505, "密码错误");
				};
			};
		})
	},
	post: function (req, res) {
		var data = req.body;
		data.type ? tablename = "teacher" : tablename = "student";
		console.log(tablename);
		req.models[tablename].find({ name: data.name }, function (err, result) {
			if (err) {
				res.send(500, err);
			} else if (!result.length) {
				data.pwd = md5(data.repwd);
				var _id = (new Date()).getTime().toString();
				data.type ? data.tid = "t" + _id : data.sid = "s" + _id;
				req.models[tablename].create($.extend({}, data), function (newusererr, newuser) {
					if (newusererr) {
						res.send(500, newusererr);
					} else {
						var nowdate = new Date();
						var _nowdate = nowdate.getFullYear() + "-" + (nowdate.getMonth() + 1) + "-" + nowdate.getDate();
						var calendar = {
							id: (new Date()).getTime(),
							start: _nowdate,
							end: " " + "24:00:00",
							title: "恭喜您成功注册成本站会员",
							color: "#4688f7",
							sid: newuser.sid,
							tid: newuser.tid
						};
						req.models["calendar"].create($.extend({}, calendar), function (calendarerr, newcalendar) {
							if (calendarerr) {
								res.send(500, calendarerr);
							} else {
								res.send(newuser);
								res.end();
							}
						});
					}
				});
			} else {
				res.send(403, "more");
				res.end();
			}
		});
	}
};